import React, { useState } from 'react';
import { Card, Button, Checkbox, message, Typography, Progress, Alert } from 'antd';
import { DeleteOutlined, FileOutlined, LoadingOutlined, FolderOpenOutlined } from '@ant-design/icons';

// 检查是否在Tauri环境中运行
const isTauriEnvironment = typeof window !== 'undefined' && 'window' in globalThis && '__TAURI__' in (window as any);

const { Title, Paragraph, Text } = Typography;

interface DeleteResult {
  totalDeleted: number;
  deletedFiles: string[];
  error?: string;
}

const FolderCleanup: React.FC = () => {
  const [selectedFolder, setSelectedFolder] = useState<string>('');
  const [includeSubfolders, setIncludeSubfolders] = useState<boolean>(false);
  const [isProcessing, setIsProcessing] = useState<boolean>(false);
  const [progress, setProgress] = useState<number>(0);
  const [result, setResult] = useState<DeleteResult | null>(null);
  const [error, setError] = useState<string>('');

  // 使用HTML5文件API选择文件夹
  const selectFolder = async () => {
    try {
      if (isTauriEnvironment) {
        // Tauri环境 - 使用Tauri的对话框API选择文件夹
        const { dialog } = (window as any).__TAURI__;
        const folder = await dialog.open({
          directory: true,
          multiple: false,
          title: '选择要清理的文件夹'
        });
        
        if (folder) {
          const folderPath = Array.isArray(folder) ? folder[0] : folder;
          setSelectedFolder(folderPath);
          setError('');
          setResult(null);
          message.success(`已选择文件夹: ${folderPath}`);
        }
      } else {
        // 浏览器环境 - 使用HTML5文件API
        // 创建一个隐藏的文件输入元素，支持文件夹选择
        const input = document.createElement('input');
        input.type = 'file';
        // 使用类型断言处理非标准属性
        (input as any).webkitdirectory = true;
        (input as any).mozdirectory = true;
        (input as any).directory = true;
        
        input.onchange = (e) => {
          const target = e.target as HTMLInputElement;
          if (target.files && target.files.length > 0) {
            // 获取文件夹路径（浏览器安全限制下只能获取相对路径或文件夹名）
            const firstFile = target.files[0];
            const folderName = firstFile.webkitRelativePath.split('/')[0];
            setSelectedFolder(folderName);
            setError('');
            setResult(null);
            message.success(`已选择文件夹: ${folderName}`);
          }
        };
        
        input.click();
      }
    } catch (err) {
      console.error('选择文件夹时出错:', err);
      message.error('选择文件夹时出错');
    }
  };

  const deleteBakFiles = async () => {
    if (!selectedFolder) {
      message.warning('请先选择文件夹');
      return;
    }

    setIsProcessing(true);
    setProgress(0);
    setError('');
    setResult(null);

    try {
      let totalDeleted = 0;
      const deletedFiles: string[] = [];

      // 模拟进度更新
      const progressInterval = setInterval(() => {
        setProgress(prev => {
          if (prev >= 90) {
            clearInterval(progressInterval);
            return prev;
          }
          return prev + 10;
        });
      }, 500);

      if (isTauriEnvironment) {
        // Tauri环境 - 执行真实的文件删除操作
        const { fs, path } = (window as any).__TAURI__;
        
        // 递归查找并删除.bak文件
        const deleteBakFilesRecursive = async (folderPath: string) => {
          try {
            const entries = await fs.readDir(folderPath);
            
            for (const entry of entries) {
              const fullPath = path.join(folderPath, entry.name);
              
              if (entry.type === 'file' && entry.name.endsWith('.bak')) {
                // 删除.bak文件
                await fs.removeFile(fullPath);
                deletedFiles.push(fullPath);
                totalDeleted++;
              } else if (entry.type === 'directory' && includeSubfolders) {
                // 递归处理子文件夹
                await deleteBakFilesRecursive(fullPath);
              }
            }
          } catch (err) {
            console.error(`处理文件夹 ${folderPath} 时出错:`, err);
            // 继续处理其他文件，不中断整个操作
          }
        };

        // 开始删除操作
        await deleteBakFilesRecursive(selectedFolder);
        
        clearInterval(progressInterval);
        setProgress(100);
        setResult({ totalDeleted, deletedFiles });
        
        if (totalDeleted > 0) {
          message.success(`删除完成，共处理 ${totalDeleted} 个.bak文件`);
        } else {
          message.info('未找到.bak文件');
        }
      } else {
        // 浏览器环境 - 模拟操作
        await new Promise(resolve => setTimeout(resolve, 2000));
        
        // 根据是否包含子文件夹生成不同的文件列表
        totalDeleted = Math.floor(Math.random() * 10) + 1;
        for (let i = 0; i < totalDeleted; i++) {
          if (includeSubfolders && i % 3 === 0) {
            // 模拟子文件夹中的文件
            deletedFiles.push(`${selectedFolder}/subfolder/file${i + 1}.bak`);
          } else {
            // 模拟根文件夹中的文件
            deletedFiles.push(`${selectedFolder}/file${i + 1}.bak`);
          }
        }

        clearInterval(progressInterval);
        setProgress(100);
        setResult({ totalDeleted, deletedFiles });
        message.success(`模拟删除完成，共处理 ${totalDeleted} 个.bak文件`);
        message.info('注意：这是一个模拟操作，在真实环境中需要使用Node.js或Tauri的文件系统API来实际删除文件');
      }
    } catch (err) {
      console.error('删除文件时出错:', err);
      setError('删除文件时出错: ' + (err instanceof Error ? err.message : String(err)));
      message.error('删除文件时出错');
    } finally {
      setIsProcessing(false);
    }
  };

  const resetForm = () => {
    setSelectedFolder('');
    setIncludeSubfolders(false);
    setProgress(0);
    setResult(null);
    setError('');
  };

  return (
    <Card title="文件夹清理工具" style={{ width: '100%' }}>
      <div style={{ maxWidth: 800, margin: '0 auto' }}>
        <Paragraph>这个工具可以帮助您删除指定文件夹中的.bak文件，保持文件夹的整洁。</Paragraph>
        {isTauriEnvironment ? (
          <Alert
            message="Tauri桌面应用"
            description="这是一个功能完整的Tauri桌面应用，支持真实的文件系统操作，包括文件删除、重命名等高级功能。"
            type="success"
            showIcon
            style={{ marginBottom: 16 }}
          />
        ) : (
          <Alert
            message="Web环境说明"
            description="由于Web浏览器的安全限制，此演示版本仅提供文件预览功能。在实际应用中，需要使用Node.js或Tauri等框架来实际执行文件删除操作。"
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}
        
        {error && (
          <Alert
            message="错误"
            description={error}
            type="error"
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}

        <div style={{ marginBottom: 24 }}>
          <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
            <Button
              type="primary"
              icon={<FolderOpenOutlined />}
              onClick={selectFolder}
              disabled={isProcessing}
              style={{ marginRight: 16 }}
            >
              浏览文件夹
            </Button>
            <Text ellipsis style={{ maxWidth: 500 }}>
              {selectedFolder || '未选择文件夹'}
            </Text>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
            <Checkbox
              checked={includeSubfolders}
              onChange={(e) => setIncludeSubfolders(e.target.checked)}
              disabled={isProcessing}
            >
              <Text>同时删除子文件夹中的.bak文件</Text>
            </Checkbox>
          </div>

          <Button
            type="default"
            danger
            icon={<DeleteOutlined />}
            onClick={deleteBakFiles}
            disabled={isProcessing || !selectedFolder}
            style={{ marginRight: 16 }}
            loading={isProcessing}
          >
            {isProcessing ? <LoadingOutlined /> : null}
            {isTauriEnvironment ? '删除.bak文件' : '模拟删除.bak文件'}
          </Button>
          
          <Button
            onClick={resetForm}
            disabled={isProcessing}
          >
            重置
          </Button>
        </div>

        {isProcessing && (
          <Progress
            percent={progress}
            status="active"
            style={{ marginBottom: 24 }}
          />
        )}

        {result && result.totalDeleted > 0 && (
          <div style={{ marginTop: 24 }}>
            <Title level={5}>删除结果</Title>
            <Paragraph>
              成功处理 {result.totalDeleted} 个 .bak 文件
            </Paragraph>
            <div style={{ maxHeight: 300, overflowY: 'auto', border: '1px solid #f0f0f0', padding: 16, borderRadius: 4 }}>
              {result.deletedFiles.map((file, index) => (
                <div key={index} style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
                  <FileOutlined style={{ marginRight: 8, color: '#ff4d4f' }} />
                  <Text>{file}</Text>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </Card>
  );
};

export default FolderCleanup;